#include <stdio.h>
#include <util.h>
#include "libavformat/avformat.h"
#include "libswscale/swscale.h"

float t, tincr, tincr2;
int16_t *samples;
uint8_t *audio_outbuf;
int audio_outbuf_size;
int audio_input_frame_size;

/*
 * add an audio output stream
 */
static AVStream *add_audio_stream(AVFormatContext *oc, enum CodecID codec_id) {
	AVCodecContext *c;
	AVStream *st;

	st = av_new_stream(oc, 1);
	if (!st)
		fail("Could not alloc stream!");

	c = st->codec;
	c->codec_id = codec_id;
	c->codec_type = AVMEDIA_TYPE_AUDIO;

	/* put sample parameters */
	c->sample_fmt = AV_SAMPLE_FMT_S16;
	c->bit_rate = 64000;
	c->sample_rate = 44100;
	c->channels = 2;

	// some formats want stream headers to be separate
	if(oc->oformat->flags & AVFMT_GLOBALHEADER)
		c->flags |= CODEC_FLAG_GLOBAL_HEADER;

	return st;
}

static void open_audio(AVFormatContext *oc, AVStream *st) {
	AVCodecContext *c;
	AVCodec *codec;

	c = st->codec;

	/* find the audio encoder */
	codec = avcodec_find_encoder(c->codec_id);
	if (!codec)
		fail("Codec not found.");

	/* open it */
	if (avcodec_open(c, codec) < 0)
		fail("Could not open codec.");

	/* init signal generator */
	t = 0;
	tincr = 2 * M_PI * 110.0 / c->sample_rate;
	/* increment frequency by 110 Hz per second */
	tincr2 = 2 * M_PI * 110.0 / c->sample_rate / c->sample_rate;

	audio_outbuf_size = 10000;
	audio_outbuf = av_malloc(audio_outbuf_size);

	if (c->frame_size <= 1)
		fail("c->frame_size <= 1 is not expected... some PCM stuff...");

/*
00112     /* ugly hack for PCM codecs (will be removed ASAP with new PCM
00113        support to compute the input frame size in samples 
00114     if (c->frame_size <= 1) {
00115         audio_input_frame_size = audio_outbuf_size / c->channels;
00116         switch(st->codec->codec_id) {
00117         case CODEC_ID_PCM_S16LE:
00118         case CODEC_ID_PCM_S16BE:
00119         case CODEC_ID_PCM_U16LE:
00120         case CODEC_ID_PCM_U16BE:
00121             audio_input_frame_size >>= 1;
00122             break;
00123         default:
00124             break;
00125         }
	} else {
*/
		audio_input_frame_size = c->frame_size;
//	}
	samples = av_malloc(audio_input_frame_size * 2 * c->channels);
}

/* prepare a 16 bit dummy audio frame of 'frame_size' samples and 'nb_channels' channels */
static void get_audio_frame(int16_t *samples, int frame_size, int nb_channels) {
	int j, i, v;
	int16_t *q;

	q = samples;
	for(j=0;j<frame_size;j++) {
			v = (int)(sin(t) * 10000);
		for(i = 0; i < nb_channels; i++)
			*q++ = v;
		t += tincr;
		tincr += tincr2;
	}
}

static void write_audio_frame(AVFormatContext *oc, AVStream *st) {
	AVCodecContext *c;
	AVPacket pkt;
	av_init_packet(&pkt);

	c = st->codec;

	get_audio_frame(samples, audio_input_frame_size, c->channels);

	pkt.size= avcodec_encode_audio(c, audio_outbuf, audio_outbuf_size, samples);

	if (c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE)
		pkt.pts= av_rescale_q(c->coded_frame->pts, c->time_base, st->time_base);
	pkt.flags |= AV_PKT_FLAG_KEY;
	pkt.stream_index= st->index;
	pkt.data= audio_outbuf;

	/* write the compressed frame in the media file */
	if (av_interleaved_write_frame(oc, &pkt) != 0) {
		fprintf(stderr, "Error while writing audio frame\n");
		exit(1);
	}
}

static void close_audio(AVFormatContext *oc, AVStream *st) {
	avcodec_close(st->codec);

	av_free(samples);
	av_free(audio_outbuf);
}

int main() {
	printf("starting...\n");

	AVOutputFormat *fmt;
	AVFormatContext *ctx;
	AVStream *st;

	av_register_all();

	printf("register done...\n");

	char *filename="test.flv";
	fmt=av_guess_format(NULL,filename,NULL);
	if (!fmt)
		fail("unable to get format.");

	printf("audio codec: %d\n",fmt->audio_codec);

	ctx=avformat_alloc_context();
	if (!ctx)
		fail("unable to create context.");

	ctx->oformat=fmt;
	snprintf(ctx->filename, sizeof(ctx->filename), "%s", filename);

	st=add_audio_stream(ctx,fmt->audio_codec);

/*	if (av_set_parameters(ctx, NULL) < 0)
		fail("Invalid output format parameters\n");*/

	av_dump_format(ctx, 0, filename, 1);
	printf("done!!!\n");
}
